package com.vkmessenger.core.localcache;

import com.vkmessenger.net.json.FriendsResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 21.06.12
 * Time: 17:10
 */
public class FriendsCache extends ListenableEntity {

    private FriendsResponse.FriendResponse[] bestFriends;
    private FriendsResponse.FriendResponse[] allFriends;
    private Map<Long, Integer> allIndexMap = new HashMap<Long, Integer>();
    private Map<Long, Integer> bestIndexMap = new HashMap<Long, Integer>();

    public void initOrClear() {
        bestFriends = new FriendsResponse.FriendResponse[0];
        allFriends = new FriendsResponse.FriendResponse[0];
        allIndexMap.clear();
        bestIndexMap.clear();
    }

    public synchronized FriendsResponse.FriendResponse[] getAllFriends() {
        return allFriends;
    }

    public synchronized void setAllFriends(FriendsResponse.FriendResponse[] allFriends) {
        this.allFriends = allFriends;
        allIndexMap.clear();
        for (int i = 0; i < allFriends.length; ++i) {
            allIndexMap.put(Long.valueOf(allFriends[i].uid), i);
        }
        super.stateChanged(this);
    }

    public synchronized FriendsResponse.FriendResponse[] getBestFriends() {
        return bestFriends;
    }

    public synchronized void setBestFriends(FriendsResponse.FriendResponse[] bestFriends) {
        this.bestFriends = bestFriends;
        bestIndexMap.clear();
        for (int i = 0; i < bestFriends.length; ++i) {
            bestIndexMap.put(Long.valueOf(bestFriends[i].uid), i);
        }
        stateChanged(this);
    }

    public synchronized void setFriendOnlineStatus(long friendId, String online) {
        if (allIndexMap.containsKey(friendId)) allFriends[allIndexMap.get(friendId)].online = online;
        if (bestIndexMap.containsKey(friendId)) bestFriends[bestIndexMap.get(friendId)].online = online;
        stateChanged(friendId);
    }

    public synchronized Integer getIndexInAllFriends(long id) {
        if (!bestIndexMap.containsKey(id)) return null;
        return allIndexMap.get(id);
    }

    public synchronized Integer getIndexInBestFriends(long id) {
        if (!bestIndexMap.containsKey(id)) return null;
        return bestIndexMap.get(id);
    }


    ////////////Singleton...
    private static FriendsCache instance = null;

    private FriendsCache() {
        initOrClear();
    }

    public static synchronized FriendsCache getInstance() {
        if (instance == null) instance = new FriendsCache();
        return instance;
    }
}
